<template>
  <!-- title="物流标签" -->
  <div class="print-form-container">
    <!-- 固定头部 -->
    <div class="fixed-header">
      <div class="header-content">
        <h3 class="header-title">物流标签</h3>
        <div class="header-right">
          <a-button type="primary" @click="handleLogisticsEdit" class="mr-5">
            <Icon icon="i-ant-design:edit-outlined" />
            物流信息批改
          </a-button>
          <a-button type="primary" @click="handleShdwEdit" class="mr-5"><Icon icon="i-ant-design:edit-outlined" />收货单位批改</a-button>
          <a-button type="primary" @click="handlePrint"><Icon icon="i-ant-design:printer-outlined" />打印</a-button>
        </div>
      </div>
      <!-- 搜索区域 -->
      <div class="search-content">
        <div class="search-form">
          <a-button @click="handleSelectAll" class="select-btn">
            <Icon icon="i-ant-design:check-square-outlined" />
            全选
          </a-button>
          <a-button @click="handleClearSelection" class="select-btn">
            <Icon icon="i-ant-design:border-outlined" />
            清空
          </a-button>
          <a-input
            v-model:value="searchForm.invName"
            placeholder="请输入商品名称"
            class="search-input"
            @input="handleSearchInput"
            @pressEnter="handleSearch"
            allowClear
          >
            <template #prefix>
              <Icon icon="i-ant-design:search-outlined" />
            </template>
          </a-input>
          <a-input
            v-model:value="searchForm.yfdh"
            placeholder="请输入邮发代号"
            class="search-input"
            @input="handleSearchInput"
            @pressEnter="handleSearch"
            allowClear
          >
            <template #prefix>
              <Icon icon="i-ant-design:search-outlined" />
            </template>
          </a-input>
          <a-input
            v-model:value="searchForm.shdw"
            placeholder="请输入收货单位"
            class="search-input"
            @input="handleSearchInput"
            @pressEnter="handleSearch"
            allowClear
          >
            <template #prefix>
              <Icon icon="i-ant-design:search-outlined" />
            </template>
          </a-input>
          <a-button @click="handleClearSearch" class="clear-btn">
            <Icon icon="i-ant-design:clear-outlined" />
            清空
          </a-button>
        </div>
      </div>
    </div>

    <!-- 可滚动内容区域 -->
    <div class="scrollable-content">
      <!-- 空状态显示 -->
      <div v-if="filteredCardList.length === 0" class="empty-state">
        <div class="empty-content">
          <Icon icon="i-ant-design:search-outlined" class="empty-icon" />
          <h3 class="empty-title">未找到匹配的标签</h3>
          <p class="empty-description">
            请尝试调整搜索条件，或者
            <a-button type="link" @click="handleClearSearch" class="clear-link">清空搜索</a-button>
          </p>
        </div>
      </div>

      <!-- 卡片列表 -->
      <Card
        v-for="item in filteredCardList"
        :key="item.originalIndex"
        class="card-item"
        @click="handleCardClick(item.originalIndex)"
        :headStyle="headStyle"
      >
        <template #title>
          <div>
            <Checkbox :checked="selectedIndexes.includes(item.originalIndex)">
              {{ '标签' + (item.originalIndex + 1) }}
            </Checkbox>
          </div>
        </template>
        <template #extra>
          <!-- <a-button type="primary" @click="handledelete">删除</a-button> -->
          <Popconfirm
            title="是否确认删除？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="(event) => handleDeleteCard(event, item.originalIndex)"
          >
            <a-button type="primary" @click.stop>删除</a-button>
          </Popconfirm>
        </template>
        <!-- <QueryForm /> (form) => registerForm(index, form)-->
        <BasicForm
          @register="(form) => registerForm(item.originalIndex, form)"
          :form-props="createFormInstance().formProps"
        >
          <template #rdOrdersPrintList>
            <BasicTable @register="(table) => registerRdOrderRdsTable(item.originalIndex, table)" />
          </template>
        </BasicForm>
      </Card>
    </div>

    <!-- 加载更多按钮 -->
    <div v-if="hasMore || isLoading" class="load-more-container">
      <a-button
        type="primary"
        :loading="isLoading"
        @click="loadMore"
        :disabled="isLoading"
        block
        size="large"
      >
        {{ isLoading ? '加载中...' : `加载更多 (还有 ${allFilteredCards.length - filteredCardList.length} 条)` }}
      </a-button>
    </div>

    <!-- 底部状态栏 -->
    <div class="bottom-status-bar">
      <!-- 右侧：选中信息和搜索状态 -->
      <div class="status-section">
        <span v-if="selectedIndexes.length > 0" class="selection-info">
          <Icon icon="i-ant-design:check-circle-outlined" class="selection-icon" />
          已选择 {{ selectedIndexes.length }} 个标签
        </span>
        <a-divider v-if="selectedIndexes.length > 0 && isSearching" type="vertical" />
        <span v-if="isSearching" class="search-status">
          <Icon icon="i-ant-design:loading-outlined" class="search-loading" />
          搜索中...
        </span>
      </div>

      <!-- 左侧：数据统计信息 -->
      <div class="stats-section">
        <a-typography-text type="secondary">
          显示 {{ filteredCardList.length }} / {{ allFilteredCards.length }} 条标签
        </a-typography-text>
      </div>
    </div>

    <PrintModal @register="registerPrintModal" />

    <!-- 物流信息更改模态框 -->
    <BasicModal
      @register="registerLogisticsModal"
      title="物流信息更改"
      @ok="handleLogisticsConfirm"
    >
      <BasicForm @register="registerLogisticsForm" />
    </BasicModal>

    <!-- 收货单位批改模态框 -->
    <BasicModal
      @register="registerShdwModal"
      title="收货单位批改"
      @ok="handleShdwConfirm"
    >
      <BasicForm @register="registerShdwForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { Card, message, Checkbox, Radio, Popconfirm } from 'ant-design-vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { ref, unref, computed, nextTick, defineProps, watch, h } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable } from '/@/components/Table';
  import { RdOrder, getPrintFx, savePrintFx } from '/@/api/wms/rd/order/rdOrder';
  import PrintModal from '/@/components/print/printModal.vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';

  const emit = defineEmits([
    'success',
    'register',
    'deleteItem',
    'restoreData',
    'clearTableSelection',
    'addItemsToTable',
    'getTableLength',
    'update-card-data',
    'selectLabel',
    'updateLogisticsInfo',
    'updateShdw',
  ]);

  const headStyle = ref<any>({
    borderBottom: '1px solid #007aff',
  });
  const { showMessage } = useMessage();
  const { t } = useI18n('wms.rd.order.rdOrder');
  const record = ref<RdOrder>({} as RdOrder);
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();

  // 物流信息更改模态框
  const [registerLogisticsModal, { openModal: openLogisticsModal, closeModal: closeLogisticsModal }] = useModal();

  // 收货单位批改模态框
  const [registerShdwModal, { openModal: openShdwModal, closeModal: closeShdwModal }] = useModal();

  // 物流信息更改表单配置
  const [registerLogisticsForm, { validate: validateLogistics, setFieldsValue: setLogisticsFieldsValue, getFieldsValue: getLogisticsFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('到站'),
        field: 'address',
        component: 'Input',
      },
      {
        label: t('联系人'),
        field: 'shr',
        component: 'Input',
      },
      {
        label: t('联系电话'),
        field: 'phone',
        component: 'Input',
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  // 收货单位批改表单配置
  const [registerShdwForm, { validate: validateShdw, setFieldsValue: setShdwFieldsValue, getFieldsValue: getShdwFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('收货单位'),
        field: 'shdw',
        component: 'Input',
        componentProps: {
          maxlength: 64,
          placeholder: '请输入收货单位',
        },
        rules: [
          {
            required: true,
            message: '请输入收货单位',
          },
        ],
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const props = defineProps({
    rdOrderPrintList: {
      type: Array,
      default: () => [],
    },
    rdOrdeData: {
      type: Object,
      default: () => {},
    },
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('到站'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 7, md: 7, sm: 24 }, 
    },
    {
      label: t('收货单位'),
      field: 'shdw',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 7, md: 7, sm: 24 }, // 一行显示三个字段
    },
    {
      label: t('联系人'),
      field: 'shr',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 4, md: 4, sm: 24 }, // 一行显示三个字段
    },
    {
      label: t('联系电话'),
      field: 'phone',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      colProps: { lg: 5, md: 5, sm: 24 }, // 一行显示三个字段
    },
    {
      label: t('商品明细'),
      field: 'rdOrdersPrintList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdOrdersPrintList',
    },
  ];

  const selectedIndexes = ref<number[]>([]);

  // 搜索表单数据
  const searchForm = ref({
    invName: '',
    yfdh: '',
    shdw: ''
  });

  // 实际用于过滤的搜索条件（防抖后的）
  const debouncedSearchForm = ref({
    invName: '',
    yfdh: '',
    shdw: ''
  });

  // 搜索防抖定时器
  let searchTimer: NodeJS.Timeout | null = null;

  // 搜索状态
  const isSearching = ref(false);

  // 使用 Map 存储每个表单的实例
  const formInstances = new Map<number, ReturnType<typeof useForm>[1]>();

  // 使用 Map 存储每个表格的原始数据
  const originalTableData = new Map<number, any[]>();

  // 分页和虚拟滚动配置
  const pageSize = ref(50); // 每页显示的卡片数量
  const currentPage = ref(1);
  const isLoading = ref(false);

  // 计算属性：过滤后的完整卡片列表（不分页，用于缓存）
  const allFilteredCards = computed(() => {
    // 使用防抖后的搜索条件进行过滤
    if (!debouncedSearchForm.value.invName && !debouncedSearchForm.value.yfdh && !debouncedSearchForm.value.shdw) {
      // 没有搜索条件时，返回所有卡片
      return props.rdOrderPrintList.map((item, index) => ({
        ...item,
        originalIndex: index
      }));
    }

    // 有搜索条件时，进行多层过滤
    return props.rdOrderPrintList
      .map((item, index) => ({
        ...item,
        originalIndex: index
      }))
      .filter((cardItem) => {
        // 收货单位过滤（卡片级别）
        const cardShdw = cardItem.shdw || '';
        const matchCardShdw = !debouncedSearchForm.value.shdw ||
          cardShdw.toLowerCase().includes(debouncedSearchForm.value.shdw.toLowerCase());

        // 如果收货单位不匹配，直接过滤掉整个卡片
        if (!matchCardShdw) {
          return false;
        }

        // 商品名称和邮发代号过滤（商品级别）
        if (!debouncedSearchForm.value.invName && !debouncedSearchForm.value.yfdh) {
          // 如果没有商品搜索条件，且收货单位匹配，则显示该卡片
          return true;
        }

        // 检查卡片内的商品是否匹配搜索条件
        const tableData = cardItem.rdOrdersPrintList || [];
        return tableData.some((item) => {
          const invName = item.basInv?.invName || '';
          const yfdh = item.basInv?.yfdh || '';

          const matchInvName = !debouncedSearchForm.value.invName ||
            invName.toLowerCase().includes(debouncedSearchForm.value.invName.toLowerCase());
          const matchYfdh = !debouncedSearchForm.value.yfdh ||
            yfdh.toLowerCase().includes(debouncedSearchForm.value.yfdh.toLowerCase());

          return matchInvName && matchYfdh;
        });
      });
  });

  // 计算属性：当前页显示的卡片列表（分页后）
  const filteredCardList = computed(() => {
    const startIndex = 0;
    const endIndex = currentPage.value * pageSize.value;
    return allFilteredCards.value.slice(startIndex, endIndex);
  });

  // 计算属性：是否还有更多数据
  const hasMore = computed(() => {
    return filteredCardList.value.length < allFilteredCards.value.length;
  });

  const registerForm = async (index: number, form: ReturnType<typeof useForm>[1]) => {
    formInstances.set(index, form);
    await nextTick();
    form.setProps({
      labelWidth: 80,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 }, // 保持整体容器为 24，让子字段通过 colProps 控制布局
      // disabled: true,
    });
    // 设置表单数据
    setTimeout(() => {
      form.setFieldsValue(props.rdOrderPrintList[index]);
    }, 100);
  };
  // 使用 Map 存储每个表格的实例
  const rdOrderRdsTables = new Map<number, ReturnType<typeof useTable>[1]>();

  const registerRdOrderRdsTable = (index: number, table: ReturnType<typeof useTable>[1]) => {
    rdOrderRdsTables.set(index, table);
    setRdOrderRdsTableData(index, props.rdOrderPrintList[index]);
  };

  async function setRdOrderRdsTableData(cardIndex: number, item: Recordable) {
    const table = rdOrderRdsTables.get(cardIndex);
    if (table) {
      console.log('表格实例有效', table);
      table.setColumns([
        {
          title: t('商品名称'),
          dataIndex: 'basInv.invName',
          width: 230,
          align: 'center',
        },
        {
          title: t('邮发代号'),
          dataIndex: 'basInv.yfdh',
          width: 60,
          align: 'center',
        },
        {
          title: t('数量'),
          dataIndex: 'iqty',
          width: 60,
          align: 'left',
        },
      ]);
      table.setProps({
        rowKey: 'id',
        pagination: false,
        bordered: true,
        size: 'small',
        inset: true,
        indexColumnProps: {
          width: 50,
        },
        actionColumn: {
          width: 60,
          actions: (record: Recordable, index: number) => [
            {
              icon: 'i-ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleRdOrderRdsDelete.bind(null, record, index, cardIndex),
              },
              // auth: 'wms:rd:order:rdOrder:edit',
            },
          ],
        },
      });
      await nextTick();

      // 保存原始数据
      const originalData = item.rdOrdersPrintList || [];
      originalTableData.set(cardIndex, originalData);

      // 设置对应 labelData 项的 rdOrderRdsList 数据
      console.log('准备设置表格数据', item.rdOrderRdsList, table.getColumns());

      try {
        // 应用搜索过滤
        const filteredData = filterTableData(originalData);
        table.setTableData(filteredData);
        console.log('表格数据设置完成');
        // 移除 table.reload() 调用以避免递归更新
        // table.reload();
      } catch (error) {
        console.error('表格数据设置失败:', error);
      }
    }
  }

  const createFormInstance = () =>
    useForm({
      labelWidth: 80,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 }, // 保持整体容器为 24，让子字段通过 colProps 控制布局
      // disabled: true,
    });

  // 防抖搜索函数
  const debouncedSearch = () => {
    if (searchTimer) {
      clearTimeout(searchTimer);
    }

    // 显示搜索状态
    isSearching.value = true;

    searchTimer = setTimeout(() => {
      try {
        // 更新防抖后的搜索条件
        debouncedSearchForm.value.invName = searchForm.value.invName;
        debouncedSearchForm.value.yfdh = searchForm.value.yfdh;
        debouncedSearchForm.value.shdw = searchForm.value.shdw;

        // 搜索时重置分页
        resetPagination();

        // 对所有表格应用搜索过滤
        rdOrderRdsTables.forEach((table, cardIndex) => {
          const originalData = originalTableData.get(cardIndex) || [];
          const filteredData = filterTableData(originalData);
          table.setTableData(filteredData);
        });
      } finally {
        // 隐藏搜索状态
        isSearching.value = false;
      }
    }, 300); // 300ms 防抖延迟
  };

  // 监听搜索输入变化
  const handleSearchInput = () => {
    debouncedSearch();
  };

  // 搜索过滤函数（用于表格内商品数据过滤）
  function filterTableData(data: any[]) {
    // 只对商品名称和邮发代号进行过滤，收货单位在卡片级别已经过滤
    if (!debouncedSearchForm.value.invName && !debouncedSearchForm.value.yfdh) {
      return data;
    }

    return data.filter((item) => {
      const invName = item.basInv?.invName || '';
      const yfdh = item.basInv?.yfdh || '';

      const matchInvName = !debouncedSearchForm.value.invName ||
        invName.toLowerCase().includes(debouncedSearchForm.value.invName.toLowerCase());
      const matchYfdh = !debouncedSearchForm.value.yfdh ||
        yfdh.toLowerCase().includes(debouncedSearchForm.value.yfdh.toLowerCase());

      return matchInvName && matchYfdh;
    });
  }

  // 处理搜索（立即执行，用于回车或按钮点击）
  function handleSearch() {
    // 清除防抖定时器
    if (searchTimer) {
      clearTimeout(searchTimer);
    }

    // 立即更新防抖后的搜索条件
    debouncedSearchForm.value.invName = searchForm.value.invName;
    debouncedSearchForm.value.yfdh = searchForm.value.yfdh;
    debouncedSearchForm.value.shdw = searchForm.value.shdw;

    // 搜索时重置分页
    resetPagination();

    // 对所有表格应用搜索过滤
    rdOrderRdsTables.forEach((table, cardIndex) => {
      const originalData = originalTableData.get(cardIndex) || [];
      const filteredData = filterTableData(originalData);
      table.setTableData(filteredData);
    });

    // 触发计算属性重新计算（通过响应式数据变化自动触发）
    // filteredCardList 会自动重新计算
  }

  // 清空搜索
  function handleClearSearch() {
    searchForm.value.invName = '';
    searchForm.value.yfdh = '';
    searchForm.value.shdw = '';

    // 立即清空防抖后的搜索条件
    debouncedSearchForm.value.invName = '';
    debouncedSearchForm.value.yfdh = '';
    debouncedSearchForm.value.shdw = '';

    // 重置分页
    resetPagination();

    // 对所有表格应用搜索过滤
    rdOrderRdsTables.forEach((table, cardIndex) => {
      const originalData = originalTableData.get(cardIndex) || [];
      const filteredData = filterTableData(originalData);
      table.setTableData(filteredData);
    });
  }

  // 加载更多数据
  const loadMore = async () => {
    if (isLoading.value || !hasMore.value) {
      return;
    }

    try {
      isLoading.value = true;
      // 模拟加载延迟，避免过快加载
      await new Promise(resolve => setTimeout(resolve, 100));
      currentPage.value += 1;
    } finally {
      isLoading.value = false;
    }
  };

  // 重置分页
  const resetPagination = () => {
    currentPage.value = 1;
  };

  // 全选标签
  function handleSelectAll() {
    // 选择当前过滤后显示的所有标签
    selectedIndexes.value = filteredCardList.value.map(item => item.originalIndex);

    // 发送选中的标签列表
    const selectedLabels = selectedIndexes.value.map(idx => props.rdOrderPrintList[idx]).filter(Boolean);
    emit('selectLabel', selectedLabels.length > 0 ? selectedLabels : []);

    console.log('全选标签:', selectedIndexes.value);
  }

  // 清空选择
  function handleClearSelection() {
    selectedIndexes.value = [];
    emit('selectLabel', []);
    console.log('清空选择');
  }

  // 物流信息更改相关方法
  const handleLogisticsEdit = async () => {
    openLogisticsModal(true);
    await nextTick();
    if (props.rdOrdeData) {
      // 将 rdOrdeData 的值设置到表单中
      setLogisticsFieldsValue({
        address: props.rdOrdeData.address || '',
        shr: props.rdOrdeData.fperson || '',
        phone: props.rdOrdeData.fphone || '',
      });
    }
  };

  // 处理物流信息更改表单提交
  const handleLogisticsConfirm = async () => {
    try {
      // 验证表单数据
      await validateLogistics();
      // 获取表单数据
      const formValues = await getLogisticsFieldsValue();
      console.log('物流信息更改表单数据:', formValues);

      // 通过事件通知父组件更新数据
      emit('updateLogisticsInfo', formValues);

      showMessage(t('物流信息更新成功'));
      closeLogisticsModal();
    } catch (error) {
      showMessage(t('表单验证失败，请检查输入'), 'error');
      console.error('表单验证失败:', error);
    }
  };

  // 收货单位批改相关方法
  const handleShdwEdit = async () => {
    // 检查是否有选中的标签
    if (selectedIndexes.value.length === 0) {
      showMessage('请先选择标签', 'warning');
      return;
    }

    console.log('选中的标签索引:', selectedIndexes.value);
    console.log('选中的标签数据:', selectedIndexes.value.map(idx => props.rdOrderPrintList[idx]));

    // 打开收货单位批改模态框
    openShdwModal(true);
    await nextTick();

    // 如果选中的标签有相同的收货单位，则预填充
    const selectedLabels = selectedIndexes.value.map(idx => props.rdOrderPrintList[idx]).filter(Boolean);
    if (selectedLabels.length > 0) {
      const firstShdw = selectedLabels[0]?.shdw || '';
      // 检查所有选中标签的收货单位是否相同
      const allSameShdw = selectedLabels.every(label => label.shdw === firstShdw);

      if (allSameShdw && firstShdw) {
        setShdwFieldsValue({
          shdw: firstShdw,
        });
      }
    }
  };

  // 处理收货单位批改表单提交
  const handleShdwConfirm = async () => {
    try {
      // 验证表单数据
      await validateShdw();
      // 获取表单数据
      const formValues = await getShdwFieldsValue();
      console.log('收货单位批改表单数据:', formValues);

      // 更新选中标签的收货单位
      const updatedData = {
        selectedIndexes: selectedIndexes.value,
        shdw: formValues.shdw,
      };

      // 通过事件通知父组件更新数据
      emit('updateShdw', updatedData);

      showMessage(`成功批改 ${selectedIndexes.value.length} 个标签的收货单位`);
      closeShdwModal();
    } catch (error) {
      showMessage(t('表单验证失败，请检查输入'), 'error');
      console.error('表单验证失败:', error);
    }
  };
  function handleRdOrderRdsDelete(record: Recordable, index: number, cardIndex: number) {
    // 从当前标签的 rdOrdersPrintList 中移除该记录
    const currentItem = props.rdOrderPrintList[cardIndex];
    const removedItemIndex = currentItem.rdOrdersPrintList.findIndex(
      (item) => item.id === record.id,
    );
    if (removedItemIndex > -1) {
      // 获取要删除的项目，但不直接修改 props
      const removedItem = currentItem.rdOrdersPrintList[removedItemIndex];

      // 通知父组件处理数据删除和恢复
      emit('restoreData', removedItem);

      // 创建新的数组，移除指定项目
      const newRdOrdersPrintList = currentItem.rdOrdersPrintList.filter(
        (item) => item.id !== record.id
      );

      // 通知父组件更新数据
      emit('update-card-data', {
        cardIndex,
        newRdOrdersPrintList,
        shouldDeleteCard: newRdOrdersPrintList.length === 0
      });

      emit('clearTableSelection');
    }
  }
  // 清理无效的选中索引
  const cleanupInvalidSelectedIndexes = () => {
    const originalLength = selectedIndexes.value.length;

    // 过滤出有效的选中索引（对应的卡片仍然存在）
    selectedIndexes.value = selectedIndexes.value.filter((idx: number) => {
      const isValid = props.rdOrderPrintList[idx] !== undefined;
      if (!isValid) {
        console.log('清理无效的选中索引:', idx);
      }
      return isValid;
    });

    if (originalLength !== selectedIndexes.value.length) {
      console.log('已清理无效选中索引，原数量:', originalLength, '清理后数量:', selectedIndexes.value.length);

      // 发送更新后的选中标签列表
      const selectedLabels = selectedIndexes.value.map((idx: number) => props.rdOrderPrintList[idx]).filter(Boolean);
      emit('selectLabel', selectedLabels.length > 0 ? selectedLabels : []);
    }
  };

  // 监听 rdOrderPrintList 的变化，自动清理无效的选中索引
  watch(
    () => props.rdOrderPrintList,
    (newList, oldList) => {
      if (newList && oldList && newList.length !== oldList.length) {
        console.log('检测到卡片列表变化，原长度:', oldList.length, '新长度:', newList.length);
        // 延迟执行清理，确保DOM更新完成
        nextTick(() => {
          cleanupInvalidSelectedIndexes();
        });
      }
    },
    { deep: true, immediate: false }
  );

  const handleCardClick = (index: number) => {
    console.log('handleCardClick', index);

    // 检查点击的卡片是否存在（防止点击已删除的卡片）
    if (!props.rdOrderPrintList[index]) {
      console.warn('点击的卡片不存在，索引:', index);
      // 清理无效的选中索引
      cleanupInvalidSelectedIndexes();
      return;
    }

    const currentIndex = selectedIndexes.value.indexOf(index);

    if (currentIndex > -1) {
      // 如果当前项已选中，则取消选中
      selectedIndexes.value.splice(currentIndex, 1);
      console.log('取消选中标签:', index);
    } else {
      // 否则添加到选中列表
      selectedIndexes.value.push(index);
      console.log('选中标签:', index);
    }

    // 清理无效的选中索引（确保所有选中的索引都对应有效的卡片）
    cleanupInvalidSelectedIndexes();

    // 发送选中的标签列表
    const selectedLabels = selectedIndexes.value.map(idx => props.rdOrderPrintList[idx]).filter(Boolean);
    emit('selectLabel', selectedLabels.length > 0 ? selectedLabels : []);

    console.log('当前选中的标签索引:', selectedIndexes.value);
    console.log('当前选中的标签数量:', selectedLabels.length);
  };


  /**
   * 处理表单提交的函数
   *
   * 当表单提交时，该函数会被调用，并输出选中的标签数据
   */
  async function handlePrint() {

    emit('getTableLength', (tableLength: number) => {
      console.log('表格长度', tableLength);
      if (tableLength === 0) {
        console.log('提交数据', props.rdOrdeData);
        const data = props.rdOrdeData;
        let params = {
          ...data,
          rdOrdersPrintList: [],
          rdOrderPrintList: props.rdOrderPrintList,
        };
        savePrintFx(params).then((res) => {
          if (res.result === 'true') {
            let printParams = {
              ids: 'printId:' + props.rdOrdeData.printId,
              title: '封箱标签打印',
              height: '0.9',
              width: '0.7',
              fileName: '标签打印fx_100',
              uuid: res.uuid,
            };
            openPrintModal(true, printParams);
          }
          console.log(res);
        });
      } else {
        showMessage('请将商品数据全部添加到物流标签', 'error');
      }
    });

    // const data = props.rdOrdeData;
    // let params = {
    //   ...data,
    //   rdOrdersPrintList: [],
    //   rdOrderPrintList: props.rdOrderPrintList,
    // };
    // const res = await savePrintFx(params);

    // if (res.result == 'true') {
    //   let params = {
    //     ids: 'printId:' + props.rdOrdeData.printId,
    //     title: '封箱标签打印',
    //     height: '0.9',
    //     width: '0.7',
    //     fileName: '标签打印fx_100',
    //     uuid: res.uuid,
    //   };
    //   openPrintModal(true, params);
    // }
    // console.log(res);
  }

  function handleDeleteCard(event: MouseEvent, index: number) {
    console.log('handleDeleteCard', event, index, props.rdOrderPrintList);
    // 阻止事件冒泡，避免触发 handleCardClick 事件
    event.stopPropagation();

    // 获取要删除的项目，但不直接修改 props
    const deletedItem = props.rdOrderPrintList[index];
    console.log('deletedItem', deletedItem);

    // 记录删除前的选中状态，用于调试
    const beforeDeleteSelection = [...selectedIndexes.value];
    console.log('删除前的选中索引:', beforeDeleteSelection);

    // 清除对应 item 的 checkbox 选中状态并更新其他索引
    const selectedIndex = selectedIndexes.value.indexOf(index);
    if (selectedIndex > -1) {
      // 移除被删除项的选中状态
      selectedIndexes.value.splice(selectedIndex, 1);
      console.log('已清除删除项的选中状态，删除的索引:', index);
    }

    // 更新所有大于被删除索引的选中索引（因为删除后索引会前移）
    selectedIndexes.value = selectedIndexes.value.map((selectedIdx: number) => {
      const newIdx = selectedIdx > index ? selectedIdx - 1 : selectedIdx;
      if (newIdx !== selectedIdx) {
        console.log('索引更新:', selectedIdx, '->', newIdx);
      }
      return newIdx;
    });

    console.log('删除后更新的选中索引:', selectedIndexes.value);

    // 通知父组件删除项目，让父组件来处理数组的修改
    emit('deleteItem', index);

    // 如果删除的项目有数据，将数据返回到表格
    if (deletedItem && deletedItem.rdOrdersPrintList && deletedItem.rdOrdersPrintList.length > 0) {
      emit('addItemsToTable', deletedItem.rdOrdersPrintList);
    }
    emit('clearTableSelection');

    // 延迟更新选中标签通知，确保删除操作完成后再发送
    nextTick(() => {
      // 再次清理无效的选中索引，确保数据一致性
      cleanupInvalidSelectedIndexes();

      const selectedLabels = selectedIndexes.value.map((idx: number) => props.rdOrderPrintList[idx]).filter(Boolean);
      emit('selectLabel', selectedLabels.length > 0 ? selectedLabels : []);

      console.log('删除操作完成后的选中索引:', selectedIndexes.value);
      console.log('删除操作完成后的选中标签数量:', selectedLabels.length);
    });
  }

  // 添加一个标志来防止递归更新
  let isUpdating = false;
  let updateTimer: NodeJS.Timeout | null = null;

  watch(
    [() => props.rdOrderPrintList, () => props.rdOrdeData],
    async ([newRdOrderPrintList]) => {
      // 防止递归更新
      if (isUpdating) {
        return;
      }

      // 清除之前的定时器
      if (updateTimer) {
        clearTimeout(updateTimer);
      }

      // 使用防抖来避免频繁更新
      updateTimer = setTimeout(async () => {
        try {
          isUpdating = true;

          // 更新表单数据
          newRdOrderPrintList.forEach((item, index) => {
            const form = formInstances.get(index);
            if (form) {
              form.setFieldsValue(item);
            }
          });

          // 更新表格数据
          newRdOrderPrintList.forEach((item, index) => {
            const table = rdOrderRdsTables.get(index);
            if (table) {
              setRdOrderRdsTableData(index, item);
            }
          });
        } finally {
          // 使用 nextTick 确保在下一个事件循环中重置标志
          await nextTick();
          isUpdating = false;
        }
      }, 100); // 100ms 防抖延迟
    },
    { deep: true, flush: 'post' }
  );
</script>
<style scoped>
  .print-form-container {
    height: 100%;
    max-height: 100%; /* 确保不超过父容器高度 */
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
    overflow: hidden; /* 防止容器本身产生滚动条 */
  }

  /* 固定头部样式 */
  .fixed-header {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #fff;
    border-bottom: 1px solid #e8e8e8;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    padding: 0;
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    max-width: 1200px;
    margin: 0 auto;
  }

  .header-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #262626;
  }

  /* 搜索区域样式 */
  .search-content {
    padding: 12px 24px;
    background: #fafafa;
    border-top: 1px solid #e8e8e8;
  }

  .search-form {
    display: flex;
    align-items: center;
    gap: 12px;
    max-width: 1200px;
    margin: 0 auto;
  }

  .search-input {
    width: 200px;
  }

  .clear-btn,
  .select-btn {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .selection-info {
    color: #1890ff;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 8px;
    background: #e6f7ff;
    border-radius: 4px;
    border: 1px solid #91d5ff;
  }

  .selection-icon {
    font-size: 16px;
  }

  .search-status {
    color: #52c41a;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 8px;
    background: #f6ffed;
    border-radius: 4px;
    border: 1px solid #b7eb8f;
  }

  .search-loading {
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  /* 空状态样式 */
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    padding: 40px 20px;
  }

  .empty-content {
    text-align: center;
    max-width: 400px;
  }

  .empty-icon {
    font-size: 64px;
    color: #d9d9d9;
    margin-bottom: 16px;
  }

  .empty-title {
    font-size: 16px;
    color: #262626;
    margin: 0 0 8px 0;
    font-weight: 500;
  }

  .empty-description {
    font-size: 14px;
    color: #8c8c8c;
    margin: 0;
    line-height: 1.5;
  }

  .clear-link {
    padding: 0;
    height: auto;
    font-size: 14px;
  }

  /* 可滚动内容区域 */
  .scrollable-content {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 20px;
    background: #f5f5f5;
    /* 确保内容区域不会超出父容器 */
    max-height: calc(100% - 120px); /* 减去固定头部和搜索区域的高度 */
  }

  /* 单个卡片样式 */
  .card-item {
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
    border-radius: 8px;
    transition: box-shadow 0.3s ease;
    background: #fff;
  }

  .card-item:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .header-content {
      padding: 12px 16px;
    }

    .search-content {
      padding: 12px 16px;
    }

    .search-form {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;
    }

    .search-input {
      width: 100%;
    }

    .bottom-status-bar {
      flex-direction: column;
      gap: 8px;
      align-items: stretch;
      text-align: center;
    }

    .stats-section,
    .status-section {
      justify-content: center;
    }

    .status-section {
      flex-wrap: wrap;
      gap: 8px;
    }

    .scrollable-content {
      padding: 16px;
      max-height: calc(100% - 160px); /* 移动端调整高度 */
    }

    .header-title {
      font-size: 16px;
    }
  }

  .load-more-container {
    margin: 24px 0;
    text-align: center;
    padding: 0 20px;
  }

  /* 底部状态栏样式 */
  .bottom-status-bar {
    margin-top: 16px;
    padding: 12px 16px;
    border-top: 1px solid #e8e8e8;
    background-color: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 0 0 6px 6px;
    min-height: 48px;
  }

  .stats-section {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 14px;
  }

  .status-section {
    display: flex;
    align-items: center;
    gap: 12px;
  }
</style>
